﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Script.Serialization;
using System.Web.Security;
using FormAuthentication.Practice.Areas.Admin.Models.SignIn;
using FormAuthentication.Practice.Areas.Customer.Models.SignIn;
using FormAuthentication.Practice.Models;

namespace FormAuthentication.Practice
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            var authCookie1 = Request.Cookies[CookiesName.CustomerCookieName];
            if (authCookie1 != null)
            {
                var authTicket = FormsAuthentication.Decrypt(authCookie1.Value);
                var identity = new GenericIdentity(authTicket.Name, "Forms");
                var principal = new UserPrincipal(identity);

                var userData = ((FormsIdentity)(Context.User.Identity)).Ticket.UserData;

                var serializer = new JavaScriptSerializer();
                principal.User = (User)serializer.Deserialize(userData, typeof(User));

                Context.User = principal;
            }

            var authCookie2 = Request.Cookies[CookiesName.AdminCookieName];
            if (authCookie2 != null)
            {
                var authTicket = FormsAuthentication.Decrypt(authCookie2.Value);
                var identity = new GenericIdentity(authTicket.Name, "Forms");
                var principal = new AdminPrincipal(identity);

                var userData = ((FormsIdentity)(Context.User.Identity)).Ticket.UserData;

                var serializer = new JavaScriptSerializer();
                principal.User = (Admin)serializer.Deserialize(userData, typeof(Admin));

                Context.User = principal;
            }
        }
    }
}
